#include "BlueTooth.h"

void BlueTooth_Init()
{	
	
	RCC_APB2PeriphClockCmd( RCC_APB2Periph_USART1, ENABLE);
	RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOB, ENABLE);
	
	GPIO_InitTypeDef  GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7; 
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;   
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; 
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	GPIO_PinAFConfig(GPIOB,GPIO_PinSource6,GPIO_AF_USART1);
	GPIO_PinAFConfig(GPIOB,GPIO_PinSource7,GPIO_AF_USART1);
	
	USART_InitTypeDef USART_InitStruct;
	USART_InitStruct.USART_BaudRate=9600;
	USART_InitStruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
	USART_InitStruct.USART_Mode=USART_Mode_Tx | USART_Mode_Rx;
	USART_InitStruct.USART_Parity=USART_Parity_No;
	USART_InitStruct.USART_StopBits=USART_StopBits_1;
	USART_InitStruct.USART_WordLength=USART_WordLength_8b;
	USART_Init(USART1,&USART_InitStruct);
	USART_Cmd(USART1,ENABLE);
}


//接收?好像用不到，我们只需要用蓝牙发送就行了
uint8_t BlueTooth_ReceiveByte()
{
	uint8_t Serial_RxData;
	while(USART_GetFlagStatus( USART1, USART_FLAG_RXNE)==RESET);
	Serial_RxData=USART_ReceiveData(USART1);
	return Serial_RxData;
}


//发送一个字节
void BlueTooth_SendByte(uint8_t Byte)
{
	USART_SendData(USART1,Byte);
	while(USART_GetFlagStatus( USART1, USART_FLAG_TXE)==RESET);
}


//这仅仅是个工具函数
uint32_t BlueTooth_Pow(uint32_t X, uint32_t Y)
{
	uint32_t Result = 1;
	while (Y --)
	{
		Result *= X;
	}
	return Result;
}

//用蓝牙发数据(GY-86 or MOTOR)
void BlueTooth_SendData(uint32_t Number)
{
	uint32_t Temp=Number;
	uint8_t Len=0;
	while(Temp!=0)
	{
		Temp/=10;
		Len++;
	}
	uint8_t i;
	for (i = 0; i < Len; i ++)
	{
		BlueTooth_SendByte(Number / BlueTooth_Pow(10, Len - i - 1) % 10 + '0');
	}
}










